package tpavel.proxy;

import java.io.File;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Scanner;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static tpavel.proxy.PropertiesName.*;

/**
 * This main class for run application from command line
 * @author tpavel
 */
public class ConsoleApp 
{
	Logger logger = LoggerFactory.getLogger(ConsoleApp.class);
	static final String PROPERTIES_FILE_NAME = "proxy.properties";

    public static void main( String[] args )
    {
    	ConsoleApp app = new ConsoleApp();
    	app.startApplication();
    }
    
    private void startApplication() {
        logger.info("Proxy application start.");
        for(ProxyServiceProperties prop:loadProperties()) {
        	Proxy proxy = new Proxy(prop);
        	proxy.start();
    	}
        logger.info("Proxy application down.");
    }
	
    private ArrayList<ProxyServiceProperties> loadProperties() {
    	Properties prop = new Properties();
    	File f = new File(PROPERTIES_FILE_NAME);
    	logger.info("path = "+f.getAbsolutePath());
    	try  {
    		prop.load(new FileInputStream(PROPERTIES_FILE_NAME));
    	} catch (Exception exc) {
    		logger.error(String.format("Error read file properties %s", PROPERTIES_FILE_NAME), exc);
    		
    	}
    	
    	Object[] list = prop.keySet().toArray();
    	java.util.Arrays.sort(list);

    	String saveServiceName = "";
    	ProxyServiceProperties serviceProperties = null;
    	ArrayList<ProxyServiceProperties> servicePropertiesList = new ArrayList<>();
    	for(Object o:list) {
    		String propertyName = (String)o;
    		
    		logger.info(propertyName);
    		
    		StringTokenizer st = new StringTokenizer(propertyName, ".");
    		if(st.countTokens() == 2) {
    			String serviceName = st.nextToken().toUpperCase();
    			String servicePropertyName = st.nextToken().toUpperCase();
    			if(saveServiceName.equals(serviceName) == false) {
    				serviceProperties = new ProxyServiceProperties(serviceName);
    				saveServiceName = serviceName;
    				servicePropertiesList.add(serviceProperties);
    			}
  			
    			// TODO: proccess error parsing and format host name and ip
    			switch (servicePropertyName) {
					case "LOCALPORT": serviceProperties.setLocalPort(Integer.parseInt( prop.getProperty(propertyName)));		
						break;
					case "REMOTEPORT": serviceProperties.setRemotePort(Integer.parseInt( prop.getProperty(propertyName)));		
						break;
					case "REMOTEHOST": serviceProperties.setRemoteHost(prop.getProperty(propertyName));		
						break;
					default:
						break;
				}
    			
    		} else {
    			logger.error("Неверный параметр %s", propertyName);
    		}
    		
    	}
    	
    	for(ProxyServiceProperties prop2:servicePropertiesList) {
    		logger.info(prop2.toString());
    	}
    	
    	return servicePropertiesList;
    }
 
}
